#!/usr/bin/env python
# coding: utf-8

import random
import csv

def all_keys(my_dict):
    """
    Purpose: Collects all keys from the dictionary and stores them in a list
    my_dict: The question dictionary
    Return: returns the list created
    """
    question_list = []
    for key in my_dict.keys():
        question_list.append(key)
    return question_list

def question_details(key, my_dict):
    """
    Purpose: Compacts the question details from the dictionary
    kes: the key 
    my_dict: the dictionary
    Return: returns question details in a list
    """
    question = my_dict[key]["questionText"]
    opt1 = my_dict[key]["option1"]
    opt2 = my_dict[key]["option2"]
    opt3 = my_dict[key]["option3"]
    opt4 = my_dict[key]["option4"]
    answer = my_dict[key]["answer"]
    attempted = my_dict[key]["attempted"]
    return [question, opt1, opt2, opt3, opt4, answer, attempted]

def check_if_answered(key, my_dict):
    """
    Purpose: The function checks if a user has answered a specific question. 
    Helps to make sure that a question is not asked twice to the user in the same session
    key: the key
    my_dict: the dictionary
    Return: returns True or False. True means the question is already answered,
    """
    if int(my_dict[key]["attempted"]):
        return True
    else:
        return False

def mark_attempted(key, my_dict):
    """
    Purpose: The function changes the value of the attempted property in the dictionary.
    A question marked as attempted cannot be asked again
    key: the key 
    my_dict: the dictionary
    Return: returns None
    """
    my_dict[key]["attempted"] = 1

def shuffle_quiz(dictionary):
    """
    Purpose: Shuffles the keys list and selects one randomly before fetching key details from the dictionary
    dictionary: the dictionary (default=question_bank)
    Return: returns a question from the dict question_array
    """
    all_keys = list(question_bank.keys())
    random.shuffle(all_keys)
    shuffled_bank = {}
    for key in all_keys:
        shuffled_bank[key] = question_bank[key]
    return shuffled_bank

def read_data(filename):
    question_bank = {}
    f = open(filename,"r",encoding='utf-8')
    questions = list(csv.reader(f))
    for question in questions[1:]:
        question_detail = {}
        for i in range(1,len(question)):
            question_detail[questions[0][i]] = question[i]
        question_bank[question[0]] = question_detail
    return question_bank


if __name__ == "__main__":
    flag = True
    scores = 0
    #read data from csv format file
    question_bank = read_data("about_china.csv")
    while flag:
        choice = input("Thank you for your interest in this exam.\nhint: press QUIT or quit to quit (ABCD or abcd for your choice).\nPress Enter to continue:\n>>")
        if choice == 'QUIT' or choice == 'quit':
            flag = False
        else:
            print("You have one chance per question\nYou cannot go back to answer a previous question\nThe total number of questions is 10\nPress any key to start\nQUIZ STARTS NOW\n........................\n")
            answer_map = {"a": 0,"A": 0,"b": 1,"B": 1,"c": 2,"C": 2,"d": 3,"D": 3}
            correct_list = ["A","B","C","D"]
            answered_number = 0
            #one session have 10 questions
            while answered_number < 10:
                #shuffle the question
                shuffled_bank = shuffle_quiz(question_bank)
                #get the key of question bank
                question_list=all_keys(shuffled_bank)
                #check the question answered or not
                if not check_if_answered(question_list[0], question_bank):
                    details = question_details(question_list[0],shuffled_bank)
                    #print out the question and items
                    print(details[0] + "\n" + "A." + details[1] + "\n" + "B." + details[2] + "\n"+ "C." + details[3] + "\n"+ "D." + details[4] + "\n")
                    item = input(">>")
                    if item == "QUIT" or item == "quit":
                        flag = False
                        break
                    #require the user enter correctly
                    while True:
                        if item in "ABCDabcd":
                            break
                        else:
                            print("please enter correctly!\n")
                            item = input(">>")
                
                    #check the answer
                    if details[1:5].index(details[5]) == answer_map[item]:
                        scores += 1
                        # mark the answered question
                        mark_attempted(question_list[0],question_bank)
                        answered_number += 1
                        print("Congratulations! your answer is correct!\n")
                    else:
                        # mark the answered question
                        mark_attempted(question_list[0],question_bank)
                        answered_number += 1
                        print("Wrong! The correct answer is "+correct_list[details[1:5].index(details[5])]+". "+details[5]+"\n")
                    
                    
            flag = False
    print("Your score is: ",scores,".","Your correct rate is: ",str((scores/10)*100)+"%")
    print("You are welcome to take the test anytime. Bye!")







